package com.easepal802s.project.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.clj.fastble.data.BleDevice;
import com.easepal802s.project.utils.ActivityUtils;
import com.ogawa.base.Constant.BleConstant;
import com.easepal802s.project.R;
import com.easepal802s.project.observer.BleDataObserver;
import com.easepal802s.project.observer.CloseObserver;
import com.easepal802s.project.ui.fragment.AirPressureMassageFragment;
import com.easepal802s.project.ui.fragment.MassageTechniqueFragment;
import com.easepal802s.project.ui.presenter.AdvancedMassagePressenter;
import com.easepal802s.project.ui.iview.IAdvancedMassageView;
import com.easepal802s.project.ble.BleController;
import com.easepal802s.project.interfaces.NoDoubleClickListener;
import com.example.reslib.utils.ToastUtils;
import com.ogawa.base.utils.CommonUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import static com.easepal802s.project.ble.BleController.CONNECT_BREAK;
import static com.easepal802s.project.ble.BleController.CONNECT_SUCCEED;

/**
 * 高级按摩
 */
public class AdvancedMassageActivity extends BaseMvpTestActivity<AdvancedMassagePressenter, AdvancedMassageActivity> implements View.OnClickListener,IAdvancedMassageView,  CompoundButton.OnCheckedChangeListener,
        ScanShoulderActivity.onCloseScan,ShouldersAdjustmentActivity.onCloseAdjust, BleDataObserver.OnBleListerner {


    public static final int TAG_ANMOSHOUFA = 0;
    public static final int TAG_QIYAANMO = 1;
    private boolean isFirstToAdjust = true;
    /**
     * 存放内容页面
     */
    private ArrayList<Fragment> contentPage;
    private RadioButton tableft;
    private RadioButton tabright;
    private ImageView mIvStart;
    private Fragment mFrag;
    private ImageView mIvPower;
    private MyHandler myHandler;
    private String model;
    private boolean isOnChange =false;//为了防止每次收到数据都设置控件
    private boolean isOffChange =false;
    private MassageTechniqueFragment mFrangment1;
    private AirPressureMassageFragment mFrangment2;
    private boolean isFirtChange = true;
    private boolean isFirt=true;
    private boolean isStartTo;
    private int SkillResult=-1;
    private int AutoResult=10000;
    private int AirResult=-1;


    @Override
    public AdvancedMassagePressenter initPresenter() {
        return new AdvancedMassagePressenter(this);
    }

    @Override
    protected void initCreateView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_advanced_massage);
        BleDataObserver.getInst().registerBleDataObserver(this);
        myHandler = new MyHandler(this);
        initFragment();
        iniTitle();
        ScanShoulderActivity.setScanAction(this);
        ShouldersAdjustmentActivity.setAdjustAction(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BleDataObserver.getInst().removeBleDataObserver(this);
    }

    @Override
    public AdvancedMassageActivity initActivity() {
        return this;
    }

    private void initFragment() {
        contentPage = new ArrayList<Fragment>();
        mFrangment1 = new MassageTechniqueFragment();
        mFrangment2 = new AirPressureMassageFragment();
        contentPage.add(mFrangment1);
        contentPage.add(mFrangment2);
        initView();
    }

    private void iniTitle() {

        findViewById(R.id.chair_back).setOnClickListener(this);
        mIvPower =  findViewById(R.id.chair_power_close);
        mIvPower.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                if(BleController.getInst().getConnectState()!=CONNECT_SUCCEED){
                    if(BleController.getInst().getDevice()!=null){
                        BleController.getInst().connectDevice(BleController.getInst().getDevice());
                    }
                    else {
                        showBleList();
                    }

                }
                else {
                    if(BleController.getInst().getIsReseting()){
                        ToastUtils.showShortToast(AdvancedMassageActivity.this,R.string.is_reseting);
                    }
                    else {
                        BleController.getInst().sendSingleData(BleConstant.TURNING, true);
                    }
                }
            }
        });
    }


    private void initView() {

        model = getIntent().getStringExtra("model");

        tableft =  findViewById(R.id.tableft);
        tabright =  findViewById(R.id.tabright);


        tableft.setOnCheckedChangeListener(this);
        tableft.setTag(TAG_ANMOSHOUFA);
        tableft.setChecked(true);


        tabright.setOnCheckedChangeListener(this);
        tabright.setTag(TAG_QIYAANMO);

        mIvStart = findViewById(R.id.iv_switch);
        mIvStart.setOnClickListener(this);
        if(!TextUtils.isEmpty(model)){
            if(model.equals("1")){
                mFrangment1.setTab(3);
                replaceContent(TAG_ANMOSHOUFA);
            }
            else {
                replaceContent(TAG_QIYAANMO);
            }
        }
        else {
            replaceContent(TAG_ANMOSHOUFA);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.chair_back:
                finish();
                break;
            case R.id.iv_switch:
                if (CommonUtil.isFastClick()) {
                    return;
                } else {
                    BleController.getInst().sendSingleData(BleConstant.PAUSE, true);
                }

                break;
            case R.id.chair_power_close:

                break;
        }
    }

    private void replaceContent(int tag) {
//        FragmentTransaction beginTransaction = getSupportFragmentManager()
//                .beginTransaction();
//        beginTransaction.replace(R.id.advtistmentFragment, contentPage.get(tag)).commit();
        //从集合中获取相对序号的Fragment
        Fragment f = contentPage.get(tag);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
//首先判断mFrag 是否为空，如果不为，先隐藏起来，接着判断从List 获取的Fragment是否已经添加到Transaction中，如果未添加，添加后显示，如果已经添加，直接显示
        if(mFrag != null) {
            fragmentTransaction.hide(mFrag);
        }
        if(!f.isAdded()) {
            fragmentTransaction.add(R.id.advtistment_fragment, f);

        } else {
            fragmentTransaction.show(f);
        }
//将获取的Fragment 赋值给声明的Fragment 中，提交
        mFrag = f;
        fragmentTransaction.commit();

    }






    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked) {
            switch (buttonView.getId()) {
                case R.id.tableft:
                    int tagleft = (Integer) buttonView.getTag();
                    replaceContent(tagleft);
                    tableft.setBackgroundResource(R.mipmap.tab_letf);
                    tabright.setBackgroundResource(0);
                    break;

                case R.id.tabright:
                    tabright.setBackgroundResource(R.mipmap.tab_letf);
                    tableft.setBackgroundResource(0);
                    int tagright = (Integer) buttonView.getTag();
                    replaceContent(tagright);
                    break;

                default:
                    break;
            }

        }
    }


    @Override
    public void isStart(boolean isStart) {
        //暂停运行 显示运行图标 正在运行 显示暂停图标
        mIvStart.setSelected(!isStart);
    }

    @Override
    public void getPowerState() {
          if(BleController.getInst().getIsOn()){
            if(!isOnChange){
                myHandler.obtainMessage(0).sendToTarget();
                isOnChange = true;
                isOffChange = false;
            }
        }
        else {
            if(!isOffChange){
                myHandler.obtainMessage(1).sendToTarget();
                isOnChange = false;
                isOffChange = true;
            }

        }

    }

    @Override
    public void isScanning() {
        if(isFirstToAdjust){
            ActivityUtils.startScanShoulderActivity(this);
        }


    }


    @Override
    public void scanClose() {
        isFirstToAdjust = false;
//        this.finish();
    }

    @Override
    public void adjustClose() {
        this.finish();
    }

    @Override
    public void onConnectState(int state) {

    }

    @Override
    public void onTargetDeviceFind(BleDevice bleDevice) {

    }

    @Override
    public void onStarScan() {

    }

    @Override
    public void onNoDeviceFind() {

    }

    @Override
    public void onGetData(String data) {
        mBasePresenter.getDatas(data);
    }

    @Override
    public void onPowerOff() {
        if(BleController.getInst().getConnectState()==CONNECT_BREAK){
            ActivityUtils.startHomeActivity(this,"BREAK");
        }
        else {
            ActivityUtils.startHomeActivity(this,"none");
        }
        this.finish();
    }

    @Override
    public void onDataChange(String bage, int auto, int skill, int air,String name,String commond) {
        Log.e("onDataChange",isFirt+"===="+auto+"===="+AutoResult+"===="+name);

        if(isFirt) {
            AutoResult = auto;
            SkillResult = skill;
            AirResult=air;
            isFirt = false;
        }
        else {
            if(auto ==0){
                AutoResult =10000;
            }
            else  if(auto!=AutoResult){
                    if(!isStartTo){
                    isStartTo = true;
                    CloseObserver.getInst().noticeonClose();
                     this.finish();
                     ActivityUtils.startProMasDetailActivity(this,name,commond);

                }
            }

        }

    }

    @Override
    public void onShoulderAdjust(int data) {
        if(CommonUtil.isActivityTop(this.getClass(),this)&&data==1){
            ActivityUtils.startShouldersAdjustmentActivity(this);
        }
        if(data==0){
            isFirstToAdjust =true;
        }

    }

    private  class MyHandler extends Handler {
        WeakReference<AdvancedMassageActivity> mMainActivityWeakReference;

        MyHandler(AdvancedMassageActivity mAdvancedMassageActivity) {
            mMainActivityWeakReference = new WeakReference<>(mAdvancedMassageActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            final AdvancedMassageActivity mAdvancedMassageActivity = mMainActivityWeakReference.get();
            if (mAdvancedMassageActivity != null) {
                switch (msg.what) {
                    case 0:
                       mIvPower.setSelected(true);
                        break;
                    case 1:
                        mIvPower.setSelected(false);
                        break;
                    case 2:
                        mIvPower.setSelected(false);
                        break;

                }
            }
        }
    }

}
